const fs = require('fs');
const path = require('path');
const fse = require('fs-extra');
const inquirer = require('inquirer');
const Logger = require('./packages/lib/logger'); // 日志模块
const AsyncWrap = require('./packages/lib/async-wrap'); // 异步容器
const updateCssFileContent = require('./packages/lib/update-css-content');
const downloadFile = require('./packages/lib/download-file'); // 下载外部文件模块
const gitCommit = require('./packages/lib/git-commit'); // 提交代码
const gitPull = require('./packages/lib/git-pull'); // 拉取代码
const inputUrl = require('./packages/commands/input-url'); // 输入url地址
const hasAsyncProject = require('./packages/commands/has-async-project'); // 是否需要同步到项目中
const hasCommit = require('./packages/commands/git-commit'); // 是否需要提交代码
const hasPull = require('./packages/commands/git-pull'); // 是否需要拉取代码

// 项目根地址
const PROJECT_ROOT_DIR = path.join(__dirname);

// 文件存放地址
const DOWNLOAD_SAVE_PATH = path.join(PROJECT_ROOT_DIR, 'dist');

/**
 * 下载css文件
 * @param {*} cssUrl 
 * @param {*} name 
 */
async function downloadCssFile(cssUrl, name) {
	try {
		cssUrl = cssUrl.startsWith('https:') ? cssUrl : `https:${cssUrl}`;
		const TTF_URL = cssUrl.replace('.css', '.ttf');
		console.log(cssUrl);
		await downloadFile(cssUrl, `${name}.css`, DOWNLOAD_SAVE_PATH);
		await downloadFile(TTF_URL, `${name}.ttf`, DOWNLOAD_SAVE_PATH);
		Logger.success(`${name} 下载完成`);
		await updateCssFileContent(
			path.join(DOWNLOAD_SAVE_PATH, `${name}.css`),
			name,
		);
		Logger.success(`=================  ${name} 同步完成 =================`);
	} catch (error) {
		Logger.error(error);
	}
}

// 所有项目
const PROJECTS = JSON.parse(
	fs.readFileSync(path.join(PROJECT_ROOT_DIR, 'projects.json'), 'utf8'),
);

// 项目的图标地址目录
const PROJECT_ICONFONT_DIR = '/uni-app/css/iconfont';

/**
 * 写入到项目中
 */
function writeProjects(projects) {
	const promises = [];
	for (let project in projects) {
		const p = new Promise((resolve, reject) => {
			const projectPath = projects[project];
			const iconDir = path.join(projectPath, PROJECT_ICONFONT_DIR);
			fse.copy(DOWNLOAD_SAVE_PATH, iconDir)
				.then(() => {
					Logger.success(`项目${project}写入成功`);
					resolve();
				})
				.catch((err) => {
					Logger.error(`项目${project}写入失败`);
					reject();
				});
		});
		promises.push(p);
	}
	return Promise.all(promises);
}

/**
 * 项目启动
 */
async function Bootstrap() {
	Logger.success('Iconfont plugin Starting...');

    // return
	const [e1, answers] = await AsyncWrap(inquirer.prompt, {
		type: 'list',
		name: 'start',
		message: '准备好了吗？：',
		choices: ['Yes', 'No'],
	});
	if (!e1 && answers.start === 'Yes') {
		// 1、先同步app图标
		const [err, appUrl] = await AsyncWrap(inputUrl, '请输入APP图标url地址'); // app url
		if (!err && appUrl) {
			await downloadCssFile(appUrl.url, 'iconfont');
		}

		// 2、同步web图标
		const [err2, webUrl] = await AsyncWrap(
			inputUrl,
			'请输入WEB图标url地址',
        );
        // web url
		if (!err2 && webUrl) {
			await downloadCssFile(webUrl.url, 'iconfont2');
		}
		Logger.success(`运行成功，文件已经下载到：${DOWNLOAD_SAVE_PATH}`);

        // 3、是否需要拉取远端代码
        const [pullError, pull] = await AsyncWrap(hasPull);
        if (pull && pull.value === '是') {
            const [pullResErr] = await AsyncWrap(gitPull, PROJECTS);
            if (!pullResErr) {
                Logger.success(`git pull Successful!`);
            }
        }

		// 4、是否需要同步到项目
		const [err3, _hasAsyncProject] = await AsyncWrap(hasAsyncProject);
		if (!err3 && _hasAsyncProject && _hasAsyncProject.isSync === '是') {
			// 4、是否写入到配置文件的项目中
			const [writeError] = await AsyncWrap(writeProjects, PROJECTS); // 写入到项目中
			if (writeError) {
				return Logger.error('写入到项目失败！');
			}
		}

        // 5、是否需要提交代码至远端
        const [cmtErr, commit] = await AsyncWrap(hasCommit);
        if (!cmtErr && commit.value === '是') {
            await AsyncWrap(gitCommit, PROJECTS);
            Logger.success('Successful');
            return;
        }
		Logger.success('Successful');
	}
}

module.exports = {
	start: function () {
		Bootstrap();
	},
};
